package com.hontech.bread.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hontech.bread.R
import com.hontech.bread.api.productInitByServer
import com.hontech.bread.api.uploadOrder
import com.hontech.bread.api.uploadStock
import com.hontech.bread.app.runWithInit
import com.hontech.bread.device.leftPushReset
import com.hontech.bread.device.leftRotationClose
import com.hontech.bread.device.leftRotationRow
import com.hontech.bread.device.nextRow
import com.hontech.bread.device.rightPushReset
import com.hontech.bread.device.rightRotationClose
import com.hontech.bread.device.rightRotationRow
import com.hontech.bread.store.StoreCargo
import com.hontech.bread.ui.dialog.ReplenishCheckDialog
import com.hontech.bread.ui.dialog.runProg
import com.hontech.bread.ui.view.CargoState
import com.hontech.bread.utils.EmptyEdge
import com.hontech.bread.utils.currentTimestamp
import com.hontech.bread.utils.dateFormat2
import com.hontech.bread.utils.log
import com.hontech.bread.utils.onClick
import com.hontech.bread.utils.runOnUi
import com.hontech.bread.utils.runOnUiCatchAny
import com.hontech.bread.utils.stringById

class ReplenishFragment2 : Fragment() {

    private lateinit var mRva: RecyclerView
    private lateinit var mRvb: RecyclerView

    private val adapterA = Replenish2Adapter()
    private val adapterB = Replenish2Adapter()

    private var runFlag = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_replenish2, null)
        initUi(view)
        return view
    }

    private fun initUi(view: View) {
        mRva = view.findViewById(R.id.id_replenish2_rv_a)
        mRvb = view.findViewById(R.id.id_replenish2_rv_b)

        mRva.adapter = adapterA
        mRva.layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)
        mRva.edgeEffectFactory = EmptyEdge()

        mRvb.adapter = adapterB
        mRvb.layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)
        mRvb.edgeEffectFactory = EmptyEdge()

        val btnStart = view.findViewById<Button>(R.id.id_replenish2_btn_start)
        btnStart.onClick { replenish() }
    }

    override fun onResume() {
        super.onResume()
        runOnUiCatchAny { runWithInit { init() } }
    }

    private suspend fun init() {
        val leftCargos = StoreCargo.queryByCol(StoreCargo.LEFT_COL)
        val rightCargos = StoreCargo.queryByCol(StoreCargo.RIGHT_COL)

        adapterA.update(leftCargos)
        adapterB.update(rightCargos)
    }

    private suspend fun replenish() {
        if (runFlag) {
            return
        }
        runFlag = true

        try {
            val pastDue = StoreCargo.isPastDue()
            if (pastDue) {
                if (!ReplenishCheckDialog().waitConfirm()) {
                    return
                }
            }
            replenishImpl()
        } finally {
            runFlag = false
        }
    }

    private suspend fun replenishImpl() {
        runProg(
            stringById(R.string.t1733460848_371),
            stringById(R.string.t1733460848_372)
        ) { dialog ->

            dialog.setMsg(stringById(R.string.t1733460848_373))
            uploadOrder()

            dialog.setMsg(stringById(R.string.t1733460848_374))
            productInitByServer()

            leftPushReset()
            adapterA.clear()

            try {
                val aList = ArrayList<StoreCargo>()
                for (row in StoreCargo.MIN_ROW..StoreCargo.MAX_ROW) {
                    dialog.setMsg("${stringById(R.string.t1733460848_375)}:${row}${stringById(R.string.t1733460848_376)}")
                    val state = leftRotationRow(row)
                    val cargo = StoreCargo(StoreCargo.LEFT_COL, nextRow(row), state)

                    val skip = StoreCargo.isSkipCargo(StoreCargo.LEFT_COL, cargo.row)

                    log("${cargo.col}-${cargo.row} $state $skip")

                    if ((state == 0) || (!skip)) {
                        StoreCargo.updateOnce(cargo)
                    }
                    aList.add(cargo)
                    adapterA.add(aList)
                }
            } finally {
                leftRotationClose()
            }

            rightPushReset()
            adapterB.clear()
            try {
                val bList = ArrayList<StoreCargo>()
                for (row in StoreCargo.MIN_ROW..StoreCargo.MAX_ROW) {
                    dialog.setMsg("${stringById(R.string.t1733460848_377)}:${row}${stringById(R.string.t1733460848_378)}")
                    val state = rightRotationRow(row)

                    val cargo = StoreCargo(StoreCargo.RIGHT_COL, nextRow(row), state)
                    val skip = StoreCargo.isSkipCargo(StoreCargo.RIGHT_COL, cargo.row)

                    log("${cargo.col}-${cargo.row} $state $skip")
                    if ((state == 0) || (!skip)) {
                        StoreCargo.updateOnce(cargo)
                    }
                    bList.add(cargo)
                    adapterB.add(bList)
                }
            } finally {
                rightRotationClose()
            }

            dialog.setMsg(stringById(R.string.t1733460848_379))
            uploadStock()

            init()
        }
    }
}

private class Replenish2Item(view: View) : RecyclerView.ViewHolder(view) {

    private val cargoState = view.findViewById<CargoState>(R.id.id_item_cargo)
    private val tvName = view.findViewById<TextView>(R.id.id_item_tv_name)
    private val tvPast = view.findViewById<TextView>(R.id.id_item_cargo_tv_past)

    fun setUp(cargo: StoreCargo) {
        val cargoName = cargo.name()

        cargoState.setKey(cargoName)
        tvName.setTag(R.id.imageId, cargoName)

        runOnUi {

            try {
                val info = StoreCargo.getInfo(cargo.col, cargo.row)
                if (tvName.getTag(R.id.imageId) != cargoName) {
                    return@runOnUi
                }
                tvPast.text = dateFormat2(info.pastDueTimestamp)
                tvName.text = info.name
                val current = currentTimestamp()
                val pastDue = current > info.pastDueTimestamp
                if (pastDue) {
                    log(
                        "${stringById(R.string.t1733460848_380)}:${cargo.col}-${cargo.row} ${cargo.num} ${
                            stringById(
                                R.string.t1733460848_381
                            )
                        }:${current} ${stringById(R.string.t1733460848_382)}:${info.pastDueTimestamp}"
                    )
                }
                cargoState.setCargoState(cargo.num, pastDue)
            } catch (e: Exception) {
                e.printStackTrace()

                if (tvName.getTag(R.id.imageId) != cargoName) {
                    return@runOnUi
                }
                tvPast.text = ""
                tvName.text = ""
                cargoState.setCargoState(cargo.num, true)
            }
        }
    }

}

private class Replenish2Adapter : RecyclerView.Adapter<Replenish2Item>() {

    private var cargos: List<StoreCargo>? = null

    @SuppressLint("NotifyDataSetChanged")
    fun update(cs: List<StoreCargo>) {
        cargos = cs
        notifyDataSetChanged()
    }

    fun clear() {
        val count = cargos?.size ?: 0
        cargos = null
        if (count != 0) {
            notifyItemRangeRemoved(0, count)
        }
    }

    fun add(cs: List<StoreCargo>) {
        val count = cargos?.size ?: 0
        cargos = cs
        notifyItemInserted(count)
    }

    override fun getItemCount(): Int {
        return cargos?.size ?: 0
    }

    override fun onBindViewHolder(holder: Replenish2Item, position: Int) {
        val cs = cargos ?: return
        holder.setUp(cs[position])
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Replenish2Item {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.item_replenish2, parent, false)
        return Replenish2Item(view)
    }
}





















